package com.ruoyi.common.utils;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicReference;

public class DesaturateImageOpenCV {
    static {  System.load("D:\\Program Files\\opencv\\build\\java\\x64\\opencv_java490.dll"); }

    public static void main(String[] args) {
        baohedu("D:\\BaiduNetdiskDownload\\scd3.jpg");
    }

    public static void baohedu(String sourceFolderPath){
        Path sourceFolder = Paths.get(sourceFolderPath);  // 源文件夹路径
        // 目标文件夹路径

        try {
            Files.walk(sourceFolder)
                    .filter(Files::isRegularFile)
                    .forEach(path -> {
                        // 读取图像
                        Mat image = Imgcodecs.imread(path.toString());

                        if (image.empty()) {
                            System.out.println("Image not loaded!");
                            return;
                        }

                        // 转换为 HSV 色彩空间
                        Mat hsvImage = new Mat();
                        Imgproc.cvtColor(image, hsvImage, Imgproc.COLOR_BGR2HSV);

                        // 分离通道
                        java.util.List<Mat> channels = new java.util.ArrayList<>();
                        Core.split(hsvImage, channels);

                        // 调整饱和度 (S 通道)
                        Mat saturation = channels.get(1);
                        Core.multiply(saturation, new Scalar(0.25), saturation); // 0.5 表示降低饱和度一半

                        // 合并通道并转换回 BGR
                        Core.merge(channels, hsvImage);
                        Mat outputImage = new Mat();
                        Imgproc.cvtColor(hsvImage, outputImage, Imgproc.COLOR_HSV2BGR);

                        // 保存结果
                        Imgcodecs.imwrite(path.toString(), outputImage);
                        System.out.println("Image"+path.toString()+" desaturated successfully!");
                        image.release();
                        hsvImage.release();
                        outputImage.release();
                    });
        } catch (IOException e) {
            System.out.println( e.getMessage());

        }
    }
}

